package com.crm.repository;

import com.crm.pojo.SalChance;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface SalChanceRepository extends JpaRepository<SalChance, Long>, JpaSpecificationExecutor<SalChance> {
    /**
     * 根据客户姓名和概要进行模糊查询
     * @param custName 客户姓名
     * @return 返回一个集合
     * @throws Exception
     */
    @Query(nativeQuery = true, value = "select * from sal_chance where if(?1 != '', chc_cust_name like concat('%', ?1, '%'), 1 = 1) " +
            "and if(?2 != '', chc_title like concat('%', ?2, '%'), 1 = 1)")
    public List<SalChance> findSalChanceList(String custName, String title) throws Exception;

    /**
     * 根据编号和用户编号判断该关系是否为自己创建的
     * @param chcId 编号
     * @param chcCreateId 用户编号
     * @return 返回一个用户
     * @throws Exception
     */
    public SalChance findSalChanceByChcIdAndChcCreateId(Long chcId, Long chcCreateId) throws Exception;

    /**
     * 删除指定的销售信息
     * @param chcId 销售编号
     * @return 返回一个整数结果
     */
    @Modifying
    @Transactional(timeout = 10)
    @Query(value = "delete from SalChance s where s.chcId = ?1")
    public int deleteSalChanceByChcId(Long chcId) throws Exception;

    /**
     * 修改指定销售机会的状态
     * @param chcId 销售编号
     * @param chcStatus 销售状态
     * @return 返回一个整数结果
     * @throws Exception
     */
    @Modifying
    @Transactional(timeout = 10)
    @Query(value = "update SalChance c set c.chcStatus = ?1 where c.chcId = ?2")
    public int editSalChanceByChcIdAndChcStatus(String chcStatus, Long chcId) throws Exception;
}